//路由鉴权
import router from "@/router";
import nprogress from "nprogress";
import "nprogress/nprogress.css";
nprogress.configure({ showSpinner: false });
import setting from "@/setting";

//获取token数据判断用户是否登录
import useUserStore from "@/store/modules/user";
import store from "@/store";
let userStore = useUserStore(store);

//全局前置守卫

router.beforeEach(async (to: any, form: any, next: any) => {
  console.log(form);
  document.title = `${setting.title}-${to.meta.title}`;
  nprogress.start();
  let token = userStore.token;
  let username = userStore.username;
  if (token) {
    if (to.path == "/login") {
      next({ path: "/" });
    } else {
      if (username) {
        next();
      } else {
        try {
          await userStore.userInfo();
          next({ ...to });
        } catch (error) {
          await userStore.userLogout();
          next({ path: "/login", query: { redirect: to.path } });
        }
      }
    }
  } else {
    if (to.path == "/login") {
      next();
    } else {
      next({ path: "/login", query: { redirect: to.path } });
    }
  }
});

//全局后置守卫
router.afterEach((to: any, form: any) => {
  console.log(to, form);
  nprogress.done();
});
